import { Injector, Input, OnInit } from '@angular/core';
import { Zone, ZoneService, ZoneResource } from '../zone/services/zone.service';
import { MySelection } from '../base/selection';
import { APIBase } from '../base/api-base';
import { EnableStatus } from '../share/components/enable-status-text/enable-status-text.component';
import { ListBase } from '../base/list-base';
import { KeySearchComponent } from '../share/components/key-search/key-search.component';
import { SoftwareInfo } from '../software/services/software.service';
import * as _ from 'lodash';

export class ZoneResourceListBase<T extends { id: number }> extends ListBase implements OnInit {
  @Input() zone: Zone;
  @Input() searchControl: KeySearchComponent;

  constructor(_inject: Injector, private resource: ZoneResource, private zoneService = _inject.get(ZoneService)) {
    super(_inject);
  }
  readonly EnableStatus = EnableStatus;
  dataSource: APIBase<any, T>;
  manager: APIBase;
  selection = new MySelection<SoftwareInfo>('id');

  ngOnInit() {
    this.route.data.subscribe(data => {
      const zone = data['zone'];
      this.dataSource = this.zoneService.resource<any, T>(zone.id, ('select_' + this.resource) as any);
      this.manager = this.zoneService.resource(zone.id, this.resource);
    });
  }

  get selectedIDs(): number[] {
    return [...this.selection.store.keys()] as any;
  }

  async delete(...ids: number[]) {
    if (!ids.length) {
      ids = this.selectedIDs;
    }
    await this.manager.delete(ids);
    this.selection.clear();
    this.reload();
  }

  async deleteSoft(...softs: SoftwareInfo[]) {
    if (!softs.length) {
      softs = this.selection.selected;
    }
    const result = await this.sweet.confirm(
      `确定要移除[${softs.map(soft => soft.name).join(',')}]吗？`,
    );
    if (result.dismiss) {
      return;
    }
    const params = _.map(softs, soft => {
      return {
        area_id: soft.area_id,
        software_id: soft.id,
      };
		});
    await this.manager.delete(params);
    this.reload();
  }

  async enable(id?: number) {
    if (id) {
      return this.manager.batch('status', EnableStatus.Enable, [id]);
    }
    await this.manager.batch('status', EnableStatus.Enable, this.selectedIDs);
  }
  async disable(id?: number) {
    if (id) {
      return this.manager.batch('status', EnableStatus.Disable, [id]);
    }
    await this.manager.batch('status', EnableStatus.Disable, this.selectedIDs);
  }
}
